package com.xumx.service;

import com.xumx.mappers.RoleMapper;
import com.xumx.mappers.UserMapper;
import com.xumx.pojo.SysRole;
import com.xumx.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xumx on 2022/5/18 21:38
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        try {
            SysUser user = userMapper.loadUserByUsername(s);
            //System.out.println(user);
            if (user==null){
                return null;
            }
            ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<SysRole> list = roleMapper.findRoleByUserId(user.getId());
            for (SysRole role : list) {
                authorities.add(new SimpleGrantedAuthority(role.getName()));
            }
            //System.out.println(list);
            String password = encoder.encode(user.getPassword());
            //封装 SpringSecurity  需要的UserDetails 对象并返回
            UserDetails userDetails = new User(user.getName(),password,authorities);
            return userDetails;
        } catch (Exception e) {
            e.printStackTrace();
            //返回null即表示认证失败
            return null;
        }

    }

}


